from django.shortcuts import render,HttpResponse,HttpResponseRedirect
from home.models import Category,Goods,Color,Size,Brand,Ckeckcondition,GoodsImage
import json
from .models import AdminUser
from django.urls import reverse
# Create your views here.


def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        try:
            user_obj = AdminUser.objects.get(user_name = username)
        except AdminUser.DoesNotExist:
            return HttpResponse('账号或用户名不正确')
        else:
            if password == user_obj.user_pswd:
                request.session['user_id'] = user_obj.id
                request.session['identity'] = user_obj.is_admin
                if user_obj.is_admin:
                    return HttpResponseRedirect(reverse('shangpinadmin:register_merchants'))
                else:
                    return HttpResponseRedirect(reverse('shangpinadmin:goods_show',args=(user_obj.id,)))
            else:
                return HttpResponse('账号或用户名不正确')



    return render(request,'shangpinadmin/adminlogin.html')


def register_merchants(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        brand = request.POST.get('brand')
        brand_obj = Brand.objects.filter(brand_name=brand)
        if brand_obj.exists():
            return HttpResponse('当前品牌已创建过用户,去和商户协商吧')
        brand_obj = Brand.objects.create(brand_name=brand)
        user_qset = AdminUser.objects.filter(user_name=username)
        if user_qset.exists():
            return HttpResponse('账号存在')
        user_obj = AdminUser.objects.create(user_name=username,user_pswd=password,brand=brand_obj)
        return HttpResponse('创建成功')
    return render(request,'shangpinadmin/register_merchants.html')

def merchants_goods_show(request,user_id):
    user_obj = AdminUser.objects.get(pk = user_id)
    brand_obj = user_obj.brand
    goods_list = Goods.objects.filter(brand=brand_obj)
    context = {'goods_list':goods_list}
    return render(request,'shangpinadmin/goods_show.html',context)

def set_goods(request,goods_id):
    goods_obj = Goods.objects.get(pk=goods_id)
    conditions = Ckeckcondition.objects.filter(goods = goods_obj)
    if request.method == 'POST':
        info = dict(request.POST)['goodsinfo']
        print(info)
        '''
        ['name','价格','商品描述','提供发票','关键字','上架','几折','季节']
        '''
        goods_obj.good_name = info[0]
        goods_obj.price = info[1]
        goods_obj.goods_text = info[2]
        goods_obj.has_invoice = info[3]
        goods_obj.keywords = info[4]
        goods_obj.status = info[5]
        goods_obj.discount = info[6]
        goods_obj.season = info[7]
        goods_obj.save()

        myfile_list = request.FILES.getlist('file',None)
        if myfile_list:
            for myfile in myfile_list:
                goods_obj.goodsimage_set.create(image=myfile)
        return HttpResponse('保存信息成功')
    if goods_obj.has_invoice:
        has_invoice = 1
    else:
        has_invoice = 0
    if goods_obj.status:
        status = 1
    else:
        status = 0
    if goods_obj.price:
        price = goods_obj.price
    else:
        price = 0
    info_dict = {'商品名字':goods_obj.good_name,'价格':price,'商品描述':goods_obj.goods_text,
                 '是否提供发票':has_invoice,'商品搜索关键字':goods_obj.keywords,'是否上架':status,
                 '打几折':goods_obj.discount,'哪个季节的服装':goods_obj.season,
                 }
    context = {'info_dict':info_dict,'goods_obj':goods_obj,'conditions':conditions}
    return render(request,'shangpinadmin/set_goods.html',context)


def add_goods (request):
    """
    'info':  ['女士羽绒服','冬季']
    'big_class': 'big_class': ['女士', '服装', '外套', '羽绒服']
    :param request:
    :return:
    """
    try:
        user_id = request.session['user_id']
        identity = request.session['identity']
    except KeyError:
        return HttpResponse('去重新登录吧')
    if identity:
        return HttpResponse('去重新登录吧')
    user_obj = AdminUser.objects.get(pk = user_id)
    if request.method == 'POST':
        info = dict(request.POST)
        goods_class = info['big_class']
        goods_info = info['info']
        brand_obj = user_obj.brand
        goods_obj = Goods.objects.create(good_name=goods_info[0],brand=brand_obj,season=goods_info[1])
        primary_classification = Category.objects.get(name = goods_class[0])
        secondary_classification = Category.objects.get(name = goods_class[1],parent=primary_classification)
        three_classification = Category.objects.get(name = goods_class[2],parent=secondary_classification)
        if goods_class[3] == '--------------':
            goods_obj.category.add(*[primary_classification, secondary_classification, three_classification])
        else:
            four_classification = Category.objects.get(name = goods_class[3],parent=three_classification)
            goods_obj.category.add(*[primary_classification, secondary_classification, three_classification,four_classification])
        return HttpResponse ('商品以入库，请在商品管理处查看')
    class_big = Category.objects.filter(parent_id=None)

    context = {'class_big':class_big}
    return render (request, 'shangpinadmin/add_goods.html', context)

def goods_detailed(request,goods_id):
    if request.method == 'POST':
        info = dict(request.POST)
        size_text = info['size_text'][0]
        size = str(info['size'][0]).split('-')
        colors = info['colors']
        count = str(info['count'][0]).split('-')
        goods_obj = Goods.objects.get(pk = goods_id)
        size_obj = Size.objects.get(size_kind=size_text)
        if len(size) != len(count) and len(size) != len(colors):
            return HttpResponse('信息不匹配')
        for i in range(len(size)):
            count_x = count[i].split('_')
            size_x = size[i].split('_')
            if len(count_x) != len(size_x):
                return HttpResponse('信息不匹配')
            for x in range(len(count_x)):
                Ckeckcondition.objects.create(size=size_obj,color_id=colors[i],goods = goods_obj,
                                              size_name=size_x[x],good_count=count_x[x])
        return HttpResponse('保存完成')

    size_list = Size.objects.all()
    color_list = Color.objects.all()
    context = {'size_list':size_list,'color_list':color_list}
    return render(request,'shangpinadmin/goods_detailed.html',context)




def class_api(request):
    if request.method == 'GET':
        class_id  = request.GET.get('class_id')
        try:
            c = Category.objects.get(pk = class_id)
            xj_class = Category.objects.filter(parent_id = c.id)
        except TypeError:
            return HttpResponse("The address cannot be requested")

        msg = {'pk':[],'name':[]}

        for i in xj_class:
            msg['pk'].append(i.id)
            msg['name'].append(i.name)
        result = {'msg':msg}
        return HttpResponse(json.dumps(result),content_type="application/json")


